import * as actionTypes from "./constants";

import { handleCategory } from "@/utils/handle-category";
import { getCategory, getCategorySongs } from "@/services/songs";

const changeCategoryAction = (category) => ({
  type: actionTypes.CHANGE_CATEGORY,
  category
});

const changeCategorySongs = (categorySongs) => ({
  type: actionTypes.CHANGE_CATEGORY_SONGS,
  categorySongs
});

export const changeCurrentCategoryAction = (currentCategory) => ({
  type: actionTypes.CHANGE_CURRENT_CATEGORY,
  currentCategory
});

export const changeCurrentPageAction = (page) => ({
  type: actionTypes.CHANGE_CURRENT_PAGE,
  page
});

/**
 * 
 * @returns 获取类别数据
 */
export function getCategoryAction() {
  return dispatch => {
    getCategory().then(res => {
      dispatch(changeCategoryAction(handleCategory(res)));
    })
  }
};

/**
 * 
 * @param {当前页码} page
 * @returns 获取列表数据
 */
export function getCategorySongsAction() {
  return (dispatch, getState) => {
    // 1.获取currentCategory&currentPage
    const name = getState().getIn(["songs", "currentCategory"]);
    let page = getState().getIn(["songs", "currentPage"]);

    //2.如果page === 1，说明取第一页数据，那么偏移就是0；
    // if (page === 1) page = 0;
    
    //2. 每次偏移量
    page = page - 1;

    // 3.获取数据
    getCategorySongs(name, page * 35).then(res => {
      dispatch(changeCategorySongs(res));
    })
  }
}